/*
 * AbmPaciente.java
 *
 * Created on 07/06/2011, 20:45:01
 */
package com.rcn.ui;

import com.google.common.base.Strings;
import com.rcn.dal.hibernate.GestorHibernateDAO;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import com.rcn.domain.ObraSocial;
import com.rcn.domain.Paciente;
import com.rcn.exception.RaccoonException;
import com.rcn.util.UIHelper;
import java.awt.Frame;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JList;

/**
 *
 * @author Nicolas
 */
public final class AbmPaciente extends javax.swing.JDialog {

    private Frame frmPrincipal;
    private boolean nuevoPaciente;
    //pacientes actualmente en la base de datos
    private static ArrayList<Paciente> listaPacientes;

    /** Creates new form AbmPaciente */
    public AbmPaciente(Frame parent, boolean modal, Paciente paciente) {
        super(parent, modal);
        frmPrincipal=parent;
        if(paciente==null){
           nuevoPaciente=true; 
        }else{
            nuevoPaciente=false;
        }

        initComponents();
        this.cargarListaPacientes();
        this.estadoInicialComponentes();
        this.seleccionarPaciente(paciente);
        this.setPaciente(paciente);
    }
    
    // <editor-fold defaultstate="collapsed" desc="Utilidades">   
    /**
     * Visibilidad inicial de los componentes de la interfaz
     */
    public final void estadoInicialComponentes() {
        this.btnNuevo.setEnabled(true);
        this.btnEditar.setEnabled(false);
        this.btnEliminar.setEnabled(false);
        this.setEnabledPanelPaciente(false);
        cargarListaObraSocial();
        this.limpiarPanelPaciente();
    }
    
    /**
     * Blanquea todos los campos del formulario de Paciente.
     */
    public void limpiarPanelPaciente(){
        this.txtApellido.setText("");
        this.txtCalle.setText("");
        this.txtDepto.setText("");
        this.txtFechaNac.setText("");
        this.txtNombre.setText("");
        this.txtNroDocumento.setText("");
        this.txtNroDomicilio.setText("");
        this.txtPiso.setText("");
        this.txtNroOS.setText("");
        this.txtTel.setText("");
        this.cmbObraSocial.setSelectedIndex(0);
    }
    
    /**
     * <code>SetEnabled(b)</code> a todos los elementos del formulario de Paciente.
     * @param b
     */
    public void setEnabledPanelPaciente(Boolean b){
        this.txtApellido.setEnabled(b);
        this.txtCalle.setEnabled(b);
        this.txtDepto.setEnabled(b);
        this.txtFechaNac.setEnabled(b);
        this.txtNombre.setEnabled(b);
        this.txtNroDocumento.setEnabled(b);
        this.txtNroDomicilio.setEnabled(b);
        this.cmbObraSocial.setEnabled(b);
        this.txtPiso.setEnabled(b);
        this.btnCancelar.setEnabled(b);
        this.btnGuardar.setEnabled(b);
        this.txtNroOS.setEnabled(b);
        this.txtTel.setEnabled(b);
    }
    // </editor-fold>

    /**
     * Carga en el Jlist una lista de pacientes.
     */
    public void cargarListaPacientes(){
        try{
            listaPacientes=(ArrayList<Paciente>)GestorHibernateDAO.getInstance().getPacienteDAO().getAll(Paciente.class);
            actualizarListaPacientes(listaPacientes);
        }catch(RaccoonException e){
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        } 
    }

    public void actualizarListaPacientes(List<Paciente> lista){
        try{            
            UIHelper.getInstance().cargarListaPacientes(lstPacientes, lista);
            UIHelper.getInstance().cargarListaPacientes(((PrincipalRaccon)(frmPrincipal)).getLstPacientes(), lista);
        }catch(RaccoonException e){
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        } 
    }

    /**
     * carga la lista de obras sociales
     */
    public void cargarListaObraSocial(){
        try{
            List lista=GestorHibernateDAO.getInstance().getObraSocialDAO().getAll(ObraSocial.class);
            for (Object item : lista) {
                this.cmbObraSocial.addItem(item);
            }
        }catch(RaccoonException e){
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
    }

    /**
     * Carga un paciente en los campos del panel de paciente.
     * @param paciente
     */
    public void setPaciente(Paciente paciente){
        if(paciente!=null){
            this.limpiarPanelPaciente();
            this.txtApellido.setText(paciente.getApellido());
            this.txtCalle.setText(paciente.getDomicilioCalle());
            this.txtDepto.setText(paciente.getDomicilioDepto());
            this.txtNombre.setText(paciente.getNombre());
            this.txtNroDocumento.setText(String.valueOf(paciente.getNroDocumento()));
            this.txtNroDomicilio.setText(String.valueOf(paciente.getDomicilioNumero()));
            this.cmbObraSocial.setSelectedItem(paciente.getObraSocial());
            if(paciente.getDomicilioPiso()>0){
                this.txtPiso.setText(String.valueOf(paciente.getDomicilioPiso()));
            }
            this.txtNroOS.setText(paciente.getNroObraSocial());
            this.txtTel.setText(paciente.getTelefono());
            SimpleDateFormat df=new SimpleDateFormat("dd/MM/yy");
            this.txtFechaNac.setText(df.format(paciente.getFechaNacimiento()));
            this.txtTel.setText(paciente.getTelefono());
            this.txtNroOS.setText(paciente.getNroObraSocial());
        }      
    }

    /**
    * Crea un paciente a partir de los datos del formulario.
    * @return Paciente
    * @throws IllegalArgumentException Valida campos numericos, fechas y obligatorios.
    */
    public Paciente getPaciente()throws IllegalArgumentException, RaccoonException{
        Paciente paciente;
        if(nuevoPaciente){
            paciente=new Paciente();
        }else{
            paciente=UIHelper.getInstance().getPacienteFromList(lstPacientes);
        }
        //TODO si el codigo de las validaciones se utiliza mas de una vez hacer metodo aparte
        //campos obligatorios nombre y apellido        
        paciente.setApellido(this.txtApellido.getText());
        paciente.setNombre(this.txtNombre.getText());
        
        //campo obligatorio y numerico nroDocumento
        try{
            if(!Strings.isNullOrEmpty(this.txtNroDocumento.getText())){
                paciente.setNroDocumento(Integer.parseInt(this.txtNroDocumento.getText()));
            }
        }catch(NumberFormatException e){
            throw new IllegalArgumentException("El número de documento del paciente es incorrecto",e);
        }
               
        try{
            if(!Strings.isNullOrEmpty(this.txtFechaNac.getText())){
                paciente.setFechaNacimiento(UIHelper.getInstance().getValidDate(this.txtFechaNac.getText()));
            }
        }catch(RaccoonException e){
            throw new RaccoonException("La fecha de nacimiento del paciente es invalida.",e);
        }
        paciente.setDomicilioCalle(this.txtCalle.getText());
        try{
            if(!Strings.isNullOrEmpty(this.txtNroDomicilio.getText())){
                paciente.setDomicilioNumero(Integer.parseInt(this.txtNroDomicilio.getText()));
            }
            if(!Strings.isNullOrEmpty(this.txtPiso.getText())){
                 paciente.setDomicilioPiso(Integer.parseInt(this.txtPiso.getText()));
            }         
        }catch(NumberFormatException e){
            throw new IllegalArgumentException("El número de domicilio o el piso son incorrectos",e);
        }
        paciente.setDomicilioDepto(this.txtDepto.getText());
        paciente.setObraSocial((ObraSocial)cmbObraSocial.getSelectedItem());
        paciente.setNroObraSocial(txtNroOS.getText());
        paciente.setTelefono(txtTel.getText());

        return paciente;
    }

    public void seleccionarPaciente(Paciente paciente){
        int index=UIHelper.getInstance().getPacienteIndex(lstPacientes, paciente);
        lstPacientes.setSelectedIndex(index);
    }
    
    public void editarPaciente(){
        this.setEnabledPanelPaciente(true);
        nuevoPaciente=false;
        this.btnEliminar.setEnabled(false);
        this.btnEditar.setEnabled(false);
        this.txtNombre.requestFocus();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel1 = new org.edisoncor.gui.panel.Panel();
        jLabel11 = new javax.swing.JLabel();
        btnCancelar = new org.edisoncor.gui.button.ButtonAction();
        btnGuardar = new org.edisoncor.gui.button.ButtonAction();
        cmbObraSocial = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        txtPiso = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel7 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        txtDepto = new org.edisoncor.gui.textField.TextFieldRectImage();
        txtNroDomicilio = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel5 = new javax.swing.JLabel();
        txtCalle = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel4 = new javax.swing.JLabel();
        txtNroDocumento = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel9 = new javax.swing.JLabel();
        lblFechaNac = new javax.swing.JLabel();
        txtApellido = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel3 = new javax.swing.JLabel();
        txtNombre = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel2 = new javax.swing.JLabel();
        btnNuevaObraSocial = new org.edisoncor.gui.button.ButtonAction();
        txtFechaNac = new org.edisoncor.gui.textField.TextFieldRectImage();
        jLabel12 = new javax.swing.JLabel();
        txtTel = new org.edisoncor.gui.textField.TextFieldRectImage();
        lblNroOS = new javax.swing.JLabel();
        txtNroOS = new org.edisoncor.gui.textField.TextFieldRectImage();
        panel3 = new org.edisoncor.gui.panel.Panel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstPacientes = new javax.swing.JList();
        txtFiltrarPacienteNombre = new org.edisoncor.gui.textField.TextFieldRectBackground();
        jLabel6 = new javax.swing.JLabel();
        btnNuevo = new org.edisoncor.gui.button.ButtonAction();
        btnEditar = new org.edisoncor.gui.button.ButtonAction();
        btnEliminar = new org.edisoncor.gui.button.ButtonAction();
        btnVerHistorial = new org.edisoncor.gui.button.ButtonTask();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Pacientes");
        setResizable(false);

        panel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 2), "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        panel1.setColorPrimario(new java.awt.Color(89, 188, 235));
        panel1.setColorSecundario(new java.awt.Color(98, 195, 241));
        panel1.setName("panel1"); // NOI18N

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/raccoonTransparente.png"))); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        btnCancelar.setText("Cancelar");
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnGuardar.setText("Guardar");
        btnGuardar.setName("btnGuardar"); // NOI18N
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        cmbObraSocial.setMaximumSize(new java.awt.Dimension(23, 18));
        cmbObraSocial.setName("cmbObraSocial"); // NOI18N
        cmbObraSocial.setPreferredSize(new java.awt.Dimension(69, 20));

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel8.setText("Obra Social");
        jLabel8.setName("jLabel8"); // NOI18N

        txtPiso.setName("txtPiso"); // NOI18N

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel7.setText("Piso");
        jLabel7.setName("jLabel7"); // NOI18N

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel10.setText("Depto.");
        jLabel10.setName("jLabel10"); // NOI18N

        txtDepto.setName("txtDepto"); // NOI18N

        txtNroDomicilio.setName("txtNroDomicilio"); // NOI18N

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Nro.");
        jLabel5.setName("jLabel5"); // NOI18N

        txtCalle.setName("txtCalle"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Calle");
        jLabel4.setName("jLabel4"); // NOI18N

        txtNroDocumento.setName("txtNroDocumento"); // NOI18N

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel9.setText("Nro. Documento");
        jLabel9.setName("jLabel9"); // NOI18N

        lblFechaNac.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblFechaNac.setText("Fecha Nac.");
        lblFechaNac.setName("lblFechaNac"); // NOI18N

        txtApellido.setName("txtApellido"); // NOI18N

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Apellido");
        jLabel3.setName("jLabel3"); // NOI18N

        txtNombre.setName("txtNombre"); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Nombre");
        jLabel2.setName("jLabel2"); // NOI18N

        btnNuevaObraSocial.setText("Nueva");
        btnNuevaObraSocial.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btnNuevaObraSocial.setName("btnNuevaObraSocial"); // NOI18N
        btnNuevaObraSocial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevaObraSocialActionPerformed(evt);
            }
        });

        txtFechaNac.setName("txtFechaNac"); // NOI18N
        txtFechaNac.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                txtFechaNacInputMethodTextChanged(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel12.setText("Tel.");
        jLabel12.setName("jLabel12");

        txtTel.setMaximumSize(new java.awt.Dimension(69, 20));
        txtTel.setMinimumSize(new java.awt.Dimension(69, 20));
        txtTel.setName("txtTel");

        lblNroOS.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblNroOS.setText("Nro. O.S");
        lblNroOS.setName("lblNroOS");

        txtNroOS.setMaximumSize(new java.awt.Dimension(69, 20));
        txtNroOS.setMinimumSize(new java.awt.Dimension(69, 20));
        txtNroOS.setName("txtNroOS");

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panel1Layout.createSequentialGroup()
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblFechaNac, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panel1Layout.createSequentialGroup()
                                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtFechaNac, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtPiso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtApellido, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtNroDocumento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtCalle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel10))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtDepto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtNroDomicilio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(panel1Layout.createSequentialGroup()
                                .addComponent(txtTel, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                                .addComponent(cmbObraSocial, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnNuevaObraSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(63, 63, 63))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblNroOS)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNroOS, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(132, 132, 132))))
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(11, 11, 11)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFechaNac)
                    .addComponent(txtFechaNac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtNroDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCalle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtNroDomicilio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtDepto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(txtPiso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbObraSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNuevaObraSocial, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNroOS)
                    .addComponent(txtNroOS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                        .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(35, 35, 35))))
        );

        panel3.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 2), "Pacientes", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        panel3.setColorPrimario(new java.awt.Color(89, 188, 235));
        panel3.setColorSecundario(new java.awt.Color(98, 195, 241));
        panel3.setName("panel3"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        lstPacientes.setName("lstPacientes"); // NOI18N
        lstPacientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstPacientesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(lstPacientes);

        txtFiltrarPacienteNombre.setDescripcion("Busqueda");
        txtFiltrarPacienteNombre.setName("txtFiltrarPacienteNombre"); // NOI18N
        txtFiltrarPacienteNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtFiltrarPacienteNombreKeyReleased(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel6.setText("Nombre");
        jLabel6.setName("jLabel6"); // NOI18N

        btnNuevo.setText("Nuevo");
        btnNuevo.setName("btnNuevo"); // NOI18N
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar");
        btnEditar.setName("btnEditar"); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnVerHistorial.setText("Ver Historial");
        btnVerHistorial.setDefaultCapable(false);
        btnVerHistorial.setDescription("Tratamientos del Paciente");
        btnVerHistorial.setName("btnVerHistorial"); // NOI18N

        javax.swing.GroupLayout panel3Layout = new javax.swing.GroupLayout(panel3);
        panel3.setLayout(panel3Layout);
        panel3Layout.setHorizontalGroup(
            panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panel3Layout.createSequentialGroup()
                        .addComponent(jScrollPane2)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel3Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFiltrarPacienteNombre, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(10, 10, 10))
                    .addGroup(panel3Layout.createSequentialGroup()
                        .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panel3Layout.createSequentialGroup()
                                .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnVerHistorial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        panel3Layout.setVerticalGroup(
            panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel3Layout.createSequentialGroup()
                .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtFiltrarPacienteNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addComponent(btnVerHistorial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        String mensajeConfirmacion="guardó";
        try{
            Paciente paciente=this.getPaciente();            
            if(nuevoPaciente){
                GestorHibernateDAO.getInstance().getPacienteDAO().save(paciente);
                listaPacientes.add(paciente);
                cargarListaPacientes();
            }else{
                GestorHibernateDAO.getInstance().getPacienteDAO().update(paciente);
                mensajeConfirmacion="actualizó";
            }
            
        }catch(IllegalArgumentException e){
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        catch(RaccoonException e){
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        JOptionPane.showMessageDialog(this, "El paciente se "+mensajeConfirmacion+" con éxito","Información",JOptionPane.INFORMATION_MESSAGE);
        this.estadoInicialComponentes();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.limpiarPanelPaciente();
        this.setEnabledPanelPaciente(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void lstPacientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstPacientesMouseClicked
        this.setEnabledPanelPaciente(false);
        this.btnEliminar.setEnabled(true);
        this.btnEditar.setEnabled(true);
        Paciente pacienteSeleccionado=UIHelper.getInstance().getPacienteFromList(lstPacientes);
        this.setPaciente(pacienteSeleccionado);
        //TODO validar y llenar los campos con el paciente seleccionado
    }//GEN-LAST:event_lstPacientesMouseClicked

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        nuevoPaciente=true;
        this.limpiarPanelPaciente();
        this.setEnabledPanelPaciente(true);
        this.btnEditar.setEnabled(false);
        this.btnEliminar.setEnabled(false);
        this.txtNombre.requestFocus();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        editarPaciente();
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        try {
            UIHelper.getInstance().eliminarPaciente(lstPacientes, listaPacientes);
        } catch (RaccoonException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            return;
        } 
        cargarListaPacientes(); //para no tener que traer todos los pac de la bd
        JOptionPane.showMessageDialog(this, "El paciente se elimino con éxito","Información",JOptionPane.INFORMATION_MESSAGE);
        estadoInicialComponentes();
    }//GEN-LAST:event_btnEliminarActionPerformed
    
    private void txtFechaNacInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_txtFechaNacInputMethodTextChanged

    }//GEN-LAST:event_txtFechaNacInputMethodTextChanged

    private void btnNuevaObraSocialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevaObraSocialActionPerformed
        AbmObraSocial abmObraSocial = new AbmObraSocial(frmPrincipal, true);
        abmObraSocial.setLocationRelativeTo(null);
        abmObraSocial.setVisible(true);
    }//GEN-LAST:event_btnNuevaObraSocialActionPerformed

    private void txtFiltrarPacienteNombreKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtFiltrarPacienteNombreKeyReleased
        String filtroPaciente=txtFiltrarPacienteNombre.getText();
        List<Paciente> listaFiltrada=new ArrayList<Paciente>(listaPacientes);
        listaFiltrada=UIHelper.getInstance().filtrarListaPacientes(listaFiltrada, filtroPaciente.toLowerCase()); 
        actualizarListaPacientes(listaFiltrada);
    }//GEN-LAST:event_txtFiltrarPacienteNombreKeyReleased


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.edisoncor.gui.button.ButtonAction btnCancelar;
    private org.edisoncor.gui.button.ButtonAction btnEditar;
    private org.edisoncor.gui.button.ButtonAction btnEliminar;
    private org.edisoncor.gui.button.ButtonAction btnGuardar;
    private org.edisoncor.gui.button.ButtonAction btnNuevaObraSocial;
    private org.edisoncor.gui.button.ButtonAction btnNuevo;
    private org.edisoncor.gui.button.ButtonTask btnVerHistorial;
    private javax.swing.JComboBox cmbObraSocial;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblFechaNac;
    private javax.swing.JLabel lblNroOS;
    private javax.swing.JList lstPacientes;
    private org.edisoncor.gui.panel.Panel panel1;
    private org.edisoncor.gui.panel.Panel panel3;
    private org.edisoncor.gui.textField.TextFieldRectImage txtApellido;
    private org.edisoncor.gui.textField.TextFieldRectImage txtCalle;
    private org.edisoncor.gui.textField.TextFieldRectImage txtDepto;
    private org.edisoncor.gui.textField.TextFieldRectImage txtFechaNac;
    private org.edisoncor.gui.textField.TextFieldRectBackground txtFiltrarPacienteNombre;
    private org.edisoncor.gui.textField.TextFieldRectImage txtNombre;
    private org.edisoncor.gui.textField.TextFieldRectImage txtNroDocumento;
    private org.edisoncor.gui.textField.TextFieldRectImage txtNroDomicilio;
    private org.edisoncor.gui.textField.TextFieldRectImage txtNroOS;
    private org.edisoncor.gui.textField.TextFieldRectImage txtPiso;
    private org.edisoncor.gui.textField.TextFieldRectImage txtTel;
    // End of variables declaration//GEN-END:variables

}
